//
//  ZYOAuthViewController.swift
//  WBBeta1
//
//  Created by wustzhy on 16/8/10.
//  Copyright © 2016年 Yestin. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class ZYOAuthViewController: UIViewController {

    lazy var webView:UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppkey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        //设置webView代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    func setupUI(){
        self.title = "微博登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillAciton")
    }
    
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    @objc private func autoFillAciton(){
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        // js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}

extension ZYOAuthViewController: UIWebViewDelegate{
    //监控 webView将要 加载的request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            if let query = request.URL?.query {
                //获取code
                let code = query.substringFromIndex("code=".endIndex)
//                print("拿到code:\(code)")
                //请求授权
                ZYUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) -> () in
                    if !isSuccess {
                        //请求失败
                        print("webView-—getUserAccount———fail")
                        return
                    }
                        //请求成功
                    print("请求成功")
//                    let result = ZYUserAccountViewModel.sharedTools.userAccount
//                    print("缓存",result)//nil 不该这样
//                    print("归档",ZYUserAccountViewModel.sharedTools.getUserAccount())
                    
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //登录成功后，发送通知 －－ 进入welcome界面
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                    })
                })
                return false
            }
        }
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    
}

//MARK: - 请求数据
extension ZYOAuthViewController{
    // 转移 -> viewmodel
//    //获取授权
//    func getUserAccount(code:String){
//        
//        ZYNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> Void in
//                guard let res = response as? [String:AnyObject] else{
//                    return
//                }
//                //字典转模型
//                let userAccount = ZYUserAccountModel(dic: res)
//                print("请求成功")
//            }) { (error) -> Void in
//                print("请求失败")
//        }
//        
//
//    }
//    
//    //user/show用户接口---请求用户个人信息
//    func getUserInfo(userAccount:ZYUserAccountModel){
//        
//        
//        ZYNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> Void in
//            guard let res = response as? [String:AnyObject] else{
//                return
//            }
//            // 赋值，保存在model中
//            userAccount.screen_name = res["screen_name"] as? String
//            userAccount.avatar_large = res["avatar_large"] as? String
//            
//            }) { (error) -> Void in
//                print("get usershow fail:\(error)")
//        }
//        
//    }
//    
//    
}















